package com.example.commons.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.ServiceException;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * @Author dongdong
 * @Date 2022/11/15 21:50
 **/
@Component
public class OssUtil {
    private String endpoint = "oss-cn-beijing.aliyuncs.com";
    private String keyId = "LTAI5tRNraqvyMJE5pFmPrC6";
    private String keySecret = "in25VswtzdFKEPdkTFyg5BbKt7NMMt";
    private String bucketName = "dongdongoss";

    //OSS上传文件
    public  String uploadFile(MultipartFile file){
        String fileName = file.getOriginalFilename();
        String folder = contentType(fileName.substring(fileName.lastIndexOf(".") + 1));
        String objectName = folder + UUID.randomUUID() + fileName;
        //如果没有下面这两行代码，访问url将不会预览而是直接下载下来
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("image/jpg");

        OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
        try {
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(file.getBytes()), metadata);
            String[] url = getUrl(objectName).split("\\?");
            return url[0];
        } catch (IOException e) {
            throw new ServiceException("文件上传异常！请稍后重新尝试！");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    //获得URL连接
    public String getUrl(String objectName){
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        //生成URL
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        ossClient.shutdown();
        if (url != null){
            return url.toString();
        }
        return null;
    }

    //根据文件类型分配文件夹
    private String contentType(String fileType){
        fileType = fileType.toLowerCase();
        String folder = "";
        switch (fileType){
            case "bmp":
            case "gif":
            case "png":
            case "jpg":
            case "jpeg": folder = "images/";
                break;

            case "html":
            case "txt":
            case "xml": folder = "text/";
                break;

            case "map3": folder = "map3/";
                break;

            case "vsd":
            case "ppt":
            case "pptx":
            case "doc":
            case "docx": folder = "application/";
                break;
            case "mp4": folder = "video/";
                break;
        }
        return folder;
    }
}
